<template>
  <div>
    <el-form @submit.native.prevent class="query-table-form" :inline="true" :model="params">
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="客户名称查询"
          clearable
          @change="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          class="date-picker-ml"
          v-model="datePicked"
          type="daterange"
          unlink-panels
          range-separator="-"
          start-placeholder="创建日期(开始)"
          end-placeholder="创建日期(截止)"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd"
          @change="handleDateChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <c-select
          clearable
          v-model="params.approval_status"
          placeholder="项目状态"
          @change="getData()"
          :options="enumApproveStatus"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getAllData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-download" :loading="exportLoading" @click="exportAllPages">
          导出
        </el-button>
      </el-form-item>
    </el-form>

    <c-table
      border
      v-loading="loading"
      ref="table"
      class="table-sm"
      :columns="tableColumns"
      row-key="customer_related_id"
      :data="tableData"
    >
      <template v-slot:name="scope">
        <el-popover placement="top-start" title="项目经理" trigger="hover">
          <div>
            <div>{{ `A角： ${scope.row.res_a_name || '-'}；` }}</div>
            <div>{{ `B角： ${scope.row.res_b_name || '-'}；` }}</div>
          </div>
          <div slot="reference">
            <div class="status-label badge-info text-left w-100">
              <div>A角:{{ scope.row.res_a_name }}</div>
              <div>B角:{{ scope.row.res_b_name }}</div>
            </div>
          </div>
        </el-popover>
      </template>
      <template v-slot:create="scope">
        <div>
          <div>{{ scope.row.createTime || '-' }}</div>
          <div>{{ scope.row.submit_person_name || '-' }}</div>
        </div>
      </template>
      <template v-slot:credit="scope">
        <div>
          <div>{{ scope.row.period_credit || '-' }} 个月</div>
          <div>{{ scope.row.loadDateCredit || '-' }}</div>
          <div>{{ scope.row.loadEndDateCredit || '-' }}</div>
        </div>
      </template>
      <template v-slot:reply="scope">
        <div>
          <div>{{ scope.row.warranty_period || '-' }} 个月</div>
          <div>{{ scope.row.loadDate || '-' }}</div>
          <div>{{ scope.row.loadEndDate || '-' }}</div>
        </div>
      </template>

      <template v-slot:status="scope">
        <span class="badge" :class="`badge-${scope.row.registerStatusStyle}`">
          {{ scope.row.registerStatusLabel }}
        </span>
      </template>
    </c-table>
    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        :page-sizes="[15, 100, 200, 500, 1000]"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="tableCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <register-edit-dialog
      :visible.sync="registerVisible"
      :query-id="registerId"
      @success="handleSuccess"
    ></register-edit-dialog>

    <el-dialog
      :visible.sync="viewVisible"
      :close-on-click-modal="false"
      :before-close="beforeClose"
      append-to-body
      top="30px"
      width="80%"
    >
      <el-tabs>
        <el-tab-pane label="放款登记">
          <register-edit view-mode :query-id="viewId"></register-edit>
        </el-tab-pane>
        <el-tab-pane label="基本信息">
          <project-detail :query-id="viewId"></project-detail>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import hpLimitMixin from '@/bank/views/business/hplimit/mixins'
import {
  enumCustomerType,
  dataAdapter,
  enumApproveStatus,
} from '@/bank/views/business/hplimit/enum'
import RegisterEditDialog from '@/bank/views/business/hplimit/register/components/RegisterEditDialog.vue'
import ProjectDetail from '@/bank/views/business/hplimit/ProjectDetail'
import RegisterEdit from '@/bank/views/business/hplimit/register/components/RegisterEdit'

import { lastPickerShortcuts } from '@/common/plugins/tools/date'
export default {
  components: {
    RegisterEditDialog,
    ProjectDetail,
    RegisterEdit,
  },
  mixins: [hpLimitMixin],
  props: {},
  data() {
    return {
      enumApproveStatus,
      enumCustomerType,
      queryDate: [],
      order: {
        create_time: 'desc',
      },
      params: {
        index: 1,
        size: 10,
        'is_rural_dev.eq': 2,
        'channel_type.eq': 1,
        'review_approval.gte': 4,
        'review_approval.neq': 9,
        'is_register.eq': '',
      },
      tableCount: 0,
      loading: false,
      tableData: [],
      tableColumns: [
        { attrs: { label: '序号', prop: 'index', width: 80, align: 'center' } },
        {
          attrs: { label: '客户名称', prop: 'customer_name', minWidth: '120px' },
          process: (v, row) => ({
            attrs: { class: 'project-history', attrs: { 'data-history': row.is_history } },
          }),
        },

        {
          attrs: { label: '授信金额(万元)', prop: 'reply_funds', align: 'center', width: 120 },
        },
        {
          attrs: { label: '贷款金额(万元)', prop: 'warranty_amount', align: 'center', width: 120 },
        },
        {
          attrs: { label: '创建时间', prop: 'createTime', align: 'center', minWidth: '90px' },
        },
        {
          attrs: { label: '银行项目经理', prop: 'resName', align: 'center', width: 140 },
          slot: 'name',
        },
        {
          attrs: { label: '登记状态', prop: 'registerStatusLabel', align: 'center' },
          slot: 'status',
        },
        {
          attrs: { label: '操作', align: 'center', width: '120px', fixed: 'right' },
          operations: [
            {
              name: '登记',
              // icon: 'fa fa-edit',
              event: this.handlerEdit,
              ifRender: row => +(row.is_register || '') === 0,
            },
            { name: '查看', event: this.showInfo },
          ],
        },
      ],

      viewId: '',
      viewVisible: false,

      registerVisible: false,
      registerId: '',

      // 提交时间选择
      datePicked: [],
      pickerOptions: {
        shortcuts: lastPickerShortcuts,
      },
    }
  },
  computed: {
    pageStatus() {
      return this.$route.query.status || ''
    },
  },
  watch: {
    pageStatus() {
      this.params['is_register.eq'] = +this.pageStatus ? 0 : ''
      this.getData()
    },
  },
  created() {
    this.params['is_register.eq'] = +this.pageStatus ? 0 : ''
    this.getAllData()
  },
  mounted() {},
  methods: {
    handleDateChange() {
      const [start, end] = this.datePicked || []
      if (start && end) {
        this.params['create_time.gte'] = start
        this.params['create_time.lte'] = `${end} 23:59:59`
      } else {
        this.params['create_time.gte'] = ''
        this.params['create_time.lte'] = ''
      }
      this.getData()
    },
    handlerEdit(row) {
      this.registerId = row.customer_related_id || ''
      this.registerVisible = true
    },
    getAllData() {
      this.getData()
    },
    exportAllPages() {
      const { index, size, subKey, ...params } = this.params
      const requestAll = []

      for (let i = 1; i <= this.pages; i++) {
        requestAll.push(this.fetchDataTimeout({ ...params, index: i, size: 10000 }))
      }
      this.exportLoading = true
      Promise.all(requestAll)
        .then(arrRes => {
          let datas = []
          arrRes.forEach(res => {
            datas = datas.concat(res)
          })
          this.exportExcel('普惠贷-项目明细', datas)
          if (this.pages > 2) {
            this.$message.warning('正在导出请耐心等待')
          }
        })
        .finally(() => {
          this.exportLoading = false
        })
    },
    showInfo(row) {
      this.viewId = row.customer_related_id || ''
      this.viewVisible = true
    },
    beforeClose() {
      this.viewVisible = false
    },
    handleSizeChange(val) {
      this.params.size = val
      this.getAllData()
    },
    dataAdapter(item, index) {
      item = dataAdapter(item)
      item.registerStatusLabel = +(item.is_register || '') === 0 ? '待登记' : '已登记'
      item.registerStatusStyle = +(item.is_register || '') === 0 ? 'primary' : 'success'
      item.index = this.params.size * (this.params.index - 1) + index + 1
      return item
    },

    handleSuccess() {
      this.getAllData()
      this.$store.dispatch('getTaskCounthpLimit')
    },
  },
}
</script>

<style lang="scss" scoped>
.status-label {
  display: inline-block;
  padding: 0.25em 0.4em;
  font-size: 75%;
  font-weight: 700;
  line-height: 1;
  text-align: center;
  vertical-align: baseline;
  border-radius: 0.25rem;
  transition: color 0.15s;
}
</style>
